/** ###################################################################
**     Filename  : project_xgate.C
**     Project   : project_xgate
**     Processor : MC9S12XDT512BMFU
**     Version   : Driver 01.13
**     Compiler  : CodeWarrior HCS12X C Compiler
**     Date/Time : 3/24/2009, 8:51 PM
**     Abstract  :
**         Main module.
**         This module contains user's application code.
**     Settings  :
**     Contents  :
**         No public methods
**
**     (c) Copyright UNIS, a.s. 1997-2008
**     UNIS, a.s.
**     Jundrovska 33
**     624 00 Brno
**     Czech Republic
**     http      : www.processorexpert.com
**     mail      : info@processorexpert.com
** ###################################################################*/
/* MODULE project_xgate */

/* Including needed modules to compile this module/procedure */
#include "Cpu.h"
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include "Events.h"
#include "INT1_CAP.h"
#include "INT2.h"
#include "ACCEL_CS.h"
#include "SPI1_ACCEL.h"
#include "ADC_Trig.h"
#include "GEAR.h"
#include "RPM.h"
#include "Inhr1.h"
#include "SCI.h"
#include "Inhr1.h"
#include "Inhr1.h"
#include "Tim1ms.h"
#include "Tim100Hz.h"
#include "Ignition.h"
#include "IFsh1.h"
#include "IEE1.h"
#include "Diag_LED.h"
#include "ENABLE_3V.h"
#include "TmDt1.h"
#include "TACH_OUT.h"
#include "FUNCTION_SW.h"
#include "SD_CD.h"
#include "DisplayUpd.h"
#include "RF_SCI.h"
#include "Inhr2.h"
#include "SPI0_SD.h"
#include "SD_CS.h"
#include "ff_err.h"
#include "ff.h"
#include "integer.h"
#include "diskio.h"
#include "MMA7455.h"
#include "Motologger.h"


/* Include shared modules, which are used for whole project */
#include "PE_Types.h"
#include "PE_Error.h"
#include "PE_Const.h"
#include "IO_Map.h"

#include "Tach_Fifo.h"


//extern word DUTY_X;
//extern word DUTY_Y;

word max(word a,word b){
  if(a>b)
    return a;
  else
    return b;
}

word min(word a, word b){
  if(a<b)
    return a;
  else
    return b;  
}





 /* Real Time Clock */
volatile BYTE rtcYear = 106, rtcMon = 6, rtcMday = 1, rtcHour, rtcMin, rtcSec;
volatile WORD Timer;

volatile WORD TachFreq;
volatile BYTE ignition_switch_val;
byte tach_state;



DWORD get_fattime ()
{
	DWORD tmr;        
	__DI();
	tmr =	  (((DWORD)rtcYear - 80) << 25)
			| ((DWORD)rtcMon << 21)
			| ((DWORD)rtcMday << 16)
			| (WORD)(rtcHour << 11)
			| (WORD)(rtcMin << 5)
			| (WORD)(rtcSec >> 1);
	__EI();
	return tmr;
}


/* Gear defines:2k pullup to 5v, numbers are in mV 
#define GEARLERR 182
#define GEAR1THR 432
#define GEAR2THR 703
#define GEAR3THR 1156
#define GEAR4THR 1953
#define GEAR5THR 2967
#define GEAR6THR 3765
*/
#define GEARLERR 1000
#define GEAR1THR 360
#define GEAR2THR 280
#define GEAR3THR 910
#define GEAR4THR 815
#define GEAR5THR 645
#define GEAR6THR 500

word Gear_Decode(word gear_v){
  if(gear_v>GEARLERR){
    return 0;
  }else if(gear_v<(GEAR1THR +30) && gear_v >(GEAR1THR -30) ){
    return 1;
  }else if(gear_v<(GEAR2THR +30) && gear_v >(GEAR2THR -30)){
    return 2;
  }else if(gear_v<(GEAR3THR +30) && gear_v >(GEAR3THR -30)){
    return 3;
  }else if(gear_v<(GEAR4THR +30) && gear_v >(GEAR4THR -30)){
    return 4;
  }else if(gear_v<(GEAR5THR +30) && gear_v >(GEAR5THR -30)){
    return 5;
  }else if(gear_v<(GEAR6THR +30) && gear_v >(GEAR6THR -30)){
    return 6;
  }else{
    return 0;
  }
}

moto_data DisplayValues;

char display_data;

void UpdateDisplay(void){
//  LCD_Clear(0);
  DisplayValues.Turn^=0x01;
  DisplayValues.Speed = (word)((dword)DisplayValues.RPM*DisplayValues.Gear/600);

  PTT_PTT5 = 1;  
  //RF_SCI_SendChar('*');  
 // RF_SCI_SendNum(DisplayValues.RPM);RF_SCI_SendChar(',');
 // RF_SCI_SendNum(DisplayValues.Speed);RF_SCI_SendChar(',');
 // RF_SCI_SendNum(DisplayValues.Gear);RF_SCI_SendChar(',');
 // RF_SCI_SendNum(DisplayValues.Turn);RF_SCI_SendChar(',');
  RF_SCI_SendNum(DisplayValues.Accel.X);RF_SCI_SendChar(',');
  RF_SCI_SendNum(DisplayValues.Accel.Y);RF_SCI_SendChar(',');
  RF_SCI_SendNum(DisplayValues.Accel.Z);RF_SCI_SendChar(',');
/*  RF_SCI_SendNum(DisplayValues.pitch);RF_SCI_SendChar(',');
  RF_SCI_SendNum(DisplayValues.roll);RF_SCI_SendChar(',');
  RF_SCI_SendNum(DisplayValues.theta);RF_SCI_SendChar(',');*/
  RF_SCI_SendStr("\n\r");

/*  SCI_SendNum(DisplayValues.RPM);SCI_SendChar(',');
  SCI_SendNum(DisplayValues.Speed);SCI_SendChar(',');
  SCI_SendNum(DisplayValues.Gear);SCI_SendChar(',');
  SCI_SendNum(DisplayValues.Turn);SCI_SendChar(',');
  SCI_SendChar('\r');*/
  PTT_PTT5 = 0;  
 

}

unsigned short RPM_to_Tach(unsigned short RPM){
  
 return RPM/62;
  
}

unsigned short Tilt_to_Tach(short tilt){

signed short scaled;

  scaled = tilt/62;
  
  return 160 + scaled;
  
  
}

char linebuf[100];			/* Console input buffer */
BYTE Buff[512];				/* Working buffer */

FATFS fatfs;				/* File system object */
DIR dir;				/* Directory object */
FIL file1;		/* File object */

IEE1_TAddress  EEPROM_START =  IEE1_AREA_START;

#define DEBUG_SCI 0
extern word Gear_V;
extern bool NewGear;
void main(void)
{ 

  
  BYTE i;
 
  byte testdata,testdatain;
  BOOL skip = FALSE;

  Tach_TData time;
  
    int file_timer;
      
  	BYTE b1;
  	FRESULT res;
	char *ptr, *ptr2;
	long p1, p2, p3;
	WORD w1;
	DWORD dw, ofs, sect = 0;
	UINT s1, s2, cnt, blen = sizeof(Buff);

#if _USE_LFN
    static char lfn[_MAX_LFN  + 1];
    finfo.lfname = lfn;
    finfo.lfsize = sizeof(lfn);
#endif

	

  /* Write your local variable definition here */
  //Accel_TData data; //struct containing accelerometer timing measurements
//  word dx,dy;         //duty cycle, 0-10000 (0-100%), fixed point, 2 decimal
//  signed short ax,ay; //acceleration (g's) fixed point, 2 decimal
//  unsigned short tilt;
//  word xmax,xmin,ymax,ymin;
//  char c;
  /*** Processor Expert internal initialization. DON'T REMOVE THIS CODE!!! ***/
  PE_low_level_init();
  /*** End of Processor Expert internal initialization.                    ***/


  
  SCI_SendStr("MotoLogger 1.0");

  Tach_Init();  
  
  //Accelerometer Initialization
  SetUp_ModeOfSensorIon(ION_G4);
  Ion_SwitchMode(ION_STANDBY);
  StaticCalibration_Ion() ;
  tilt_Init();
  
  /*
  SCI_SendStr("Initializing File System\n");
   
   //Enable 3V Switched
  ENABLE_3V_SetVal();
  //give card time to boot
    Cpu_Delay100US(20);
  
  if(res = f_mount(0, &fatfs)){
   SCI_SendStr("Error: ");
   SCI_SendNum(res);
   SCI_SendChar('\n'); 
  }
   ptr = linebuf;
   linebuf[0]==0;

   SCI_SendStr("Finished Initialization of File System\n");
     
     if((res = f_opendir(&dirs, ptr)) == FR_OK){
           SCI_SendStr("Read Root directory\n");
           
     }
     
     // scan_files(linebuf);
       	res = f_opendir(&dir, ptr);
				if (res) { SCI_SendStr("Error: ");
                   SCI_SendNum(res);
                   SCI_SendChar('\n'); }
				
				while(TRUE) {
					res =(BYTE) f_readdir(&dir, &finfo);
					if ((res != FR_OK) || !finfo.fname[0]) break;
				
			
								
						  //  if(lfn[0]==0){  					
						        SCI_SendStr( finfo.fname);
						      }
						      else { 						      
							  	  SCI_SendStr( lfn);
						      }
								SCI_SendStr("   ");
								SCI_SendNum(finfo.fsize);
                SCI_SendStr("\n");
                 res = f_open(&file1,finfo.fname, FA_OPEN_EXISTING | FA_READ);

                 res = f_read(&file1, Buff, 20, &cnt);
                  if (!res && cnt != 0)  {
                      Buff[20]=0;
                     	SCI_SendStr(Buff);
                     	SCI_SendStr("\n");
                  }
                 res = f_close(&file1);
				}
	// Create destination file
    res = f_open(&file1, "hell.txt",FA_CREATE_ALWAYS | FA_WRITE | FA_OPEN_ALWAYS);
		  	if (res) { SCI_SendStr("open error: ");
                   SCI_SendNum(res);
                   SCI_SendChar('\n'); }
    
    res = f_printf(&file1,"fuckaduck, inc.\n");
    
    //res = f_sync(&file1);
		//res = f_write(&file1, finfo.fname, 8, &s2);
             
	if (res) { SCI_SendStr("print error: ");
                   SCI_SendNum(res);
                   SCI_SendChar('\n'); }
    res = f_sync(&file1);
    res = f_close(&file1);	
*/      
    
//	datalogging_Init("datalog");			
   
  TachFreq=80;
  tach_state =0;    
  file_timer = 30;
  DisplayUpd_Enable();
  GEAR_EnableIntChanTrigger(1);
  for(;;){
    //GEAR_Measure(FALSE); //this is done by internal timer trigger
    
    if(Tach_Fifo_Get(&time)==ERR_OK){
      DisplayValues.RPM = time;
    }    
    
    __DI();
    if(NewGear){                
      NewGear = 0;
      __EI();
      DisplayValues.Gear = Gear_Decode(Gear_V);      
    }
     __EI(); 
    if(tach_state == 0){  //RPM
      TachFreq = RPM_to_Tach(DisplayValues.RPM)  + 1;
    }else{
      TachFreq = Tilt_to_Tach(DisplayValues.roll);
    }

       
     
    __DI();
    if(display_data){ 
      display_data = 0;
      __EI();
      
      tilt_getTilt(&(DisplayValues.pitch),&(DisplayValues.roll),&(DisplayValues.theta));
      MMA7455_getVector(&(DisplayValues.Accel));
      UpdateDisplay();
    //  TACH_OUT_SetFreqHz(TachFreq);
    //  TACH_OUT_SetRatio16(32768);
      
    /*  if(file_timer > 1)  {
         datalogging_print(DisplayValues);
      }
      if(file_timer==1){
         datalogging_close();
      }
      file_timer --; 
      
       */     
    }   
    __EI();
    
   

  }
    
  

  
  

  /*** Processor Expert end of main routine. DON'T MODIFY THIS CODE!!! ***/
  for(;;){}
  /*** Processor Expert end of main routine. DON'T WRITE CODE BELOW!!! ***/
} /*** End of main routine. DO NOT MODIFY THIS TEXT!!! ***/

/* END project_xgate */
/*
** ###################################################################
**
**     This file was created by UNIS Processor Expert 2.99 [04.12]
**     for the Freescale HCS12X series of microcontrollers.
**
** ###################################################################
*/
